package com.zhdl.hardware.robot.kuka.repository.impl;

import cn.hutool.json.JSONUtil;
import com.google.common.eventbus.Subscribe;
import com.project.command.faq.event.behavior.BehaviorPerform;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.hardware.robot.kuka.repository.KukaCmdHandleDao;
import com.zhdl.modules.assemblybolt.web.req.RobotDto;
import com.zhdl.modules.tools.CommonCallback;
import com.zhdl.network.servertcp.TcpServerSendService;
import com.zhdl.network.strategy.common.ProtocolContext;
import com.zhdl.network.strategy.modbustcp.ModbusASCIIStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class KukaCmdHandleDaoImpl implements KukaCmdHandleDao {

    /**
     * 库卡机器人-网口
     */
    public String port;
    /**
     * 通信协议处理
     */
    public ProtocolContext protocolContext;
    /**
     * Callback 回调管理
     */
    public Map<String, CommonCallback<String>> commonCallbackMap = new ConcurrentHashMap<>();

    @Resource
    public BehaviorPerform behaviorPerform;

    @Override
    public void addPort(String port) {
        EventBusCenter.getEventBus().register(this);
        protocolContext = new ProtocolContext(new ModbusASCIIStrategy(port, behaviorPerform));
        this.port = port;
    }

    @Override
    public void initEvent(){
        EventBusCenter.getEventBus().register(this);
    }

    @Subscribe
    public void dataReception(RobotDto event) {
        String escape = JSONUtil.escape(event.getDecFullData());
        String cmd = currentCmd;
        log.info(escape);
        log.info("当前指令:" + currentCmd + ",返回的数据为:" + escape);
        currentCmd = "";
        commonCallbackMap.get(cmd).statusCallback(escape);
        commonCallbackMap.remove(cmd);
    }

    @Resource
    TcpServerSendService tcpServerSendService;

    String currentCmd = "";

    /**
     * 发送自定义指令
     *
     * @param cmd   指令
     * @param callback  回调
     */
    @Override
    public void kukaRobotCmd(String cmd,CommonCallback<String> callback){
        char[] charArray = cmd.toCharArray();
        StringBuilder stringBuffer = new StringBuilder();
        for (char c : charArray) {
            stringBuffer.append(Integer.toHexString(c));
        }
        String hexStr = stringBuffer.toString();
        tcpServerSendService.sendCmd(hexStr);
//        protocolContext.sendCmd(hexStr);
        commonCallbackMap.put(hexStr,callback);
        currentCmd = hexStr;
    }

}
